use std::collections::HashMap;
use std::fs::create_dir_all;
use chrono::Local;
use serde_json::{json, Map, Value};
use tracing::{debug, info};
use crate::http::get_gio;
use crate::http::http_request::{HttpRequest};
use crate::http::http_response::HttpResponse;
use crate::nosql::nosql_database::NoSqlValue;
use crate::util::cookie_parse::cookie_parse;
use crate::util::file::write_to_file;

pub fn message_handler(request: &HttpRequest, response: &mut HttpResponse) {

    let mut params = HashMap::new();

    let cleaned_body = request.body.replace('\0', "");

    let lines: Vec<&str> = cleaned_body.split('\n').collect();

    for line in lines {

        let decoded_pairs: Vec<(String, String)> = form_urlencoded::parse(line.as_bytes())
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect();

        debug!("parse url encoding decoded_pairs: {:?}", decoded_pairs);

        decoded_pairs.iter().for_each(|(key, value)| {
            params.insert(key.trim().to_string(), value.trim().to_string());
        });

        // if let Some((key, value)) = line.split_once('=') {
        //     let decoded_str = form_urlencoded::parse(value.as_bytes())
        //         .map(|(key, value)| (key.into_owned(), value.into_owned()))
        //         .collect::<Vec<(String, String)>>();
        //     params.insert(key.trim().to_string(), value.trim().to_string());
        // }
    }

    let empty = String::new();
    // 修正拼写错误
    let message = params.get("message").unwrap();

    info!("message_handler params: {:?}", message);

    let cookie = cookie_parse(request);

    // 使用 unwrap_or 处理可能的缺失情况
    let session_id = cookie.get("session_id").expect("没有session");

    info!("message_handler session_id: {:?}", session_id);

    let mut client_guard = get_gio().write().expect("拿不到锁");
    // 使用 unwrap_or 处理可能的缺失情况
    let user = client_guard.get(session_id).expect("No session found");
    info!("message_handler user: {:?}", user);


    // 反序列化 JSON 字符串回 HashMap
    let mut deserialized_params: Value = serde_json::from_str(user).unwrap();

    info!("message_handler client_guard deserialized_params: {:?}", deserialized_params["name"]);

    // 将新消息追加到 "messages" 数组中
    if let Some(messages) = deserialized_params.get_mut("messages") {
        if let Some(messages_array) = messages.as_array_mut() {
            messages_array.push(Value::String(message.to_string()));
        }
    }

    let deserialized_string = serde_json::to_string(&deserialized_params).unwrap();

    info!("message_handler client_guard deserialized_string: {:?}", deserialized_string);

    client_guard.insert(session_id.to_string(), deserialized_string.clone());

    if let Some(messages) = client_guard.get("messages"){
        info!("me_handler new messages: {:?}", messages);

        let mut new_message_object = Map::new();
        new_message_object.insert("name".to_string(), deserialized_params["name"].clone());
        new_message_object.insert("session_id".to_string(), deserialized_params["session_id"].clone());
        new_message_object.insert("message".to_string(), Value::String(message.to_string()));
        new_message_object.insert("date".to_string(), Value::String(Local::now().format("%Y-%m-%d %H:%M:%S").to_string()));
        new_message_object.insert("city".to_string(), deserialized_params["city"].clone());
        new_message_object.insert("province".to_string(), deserialized_params["province"].clone());

        debug!("message_handler new_message_object: {:?}", new_message_object);

        let mut messges_value: Value = serde_json::from_str(messages).unwrap();

        debug!("message_handler exist messages_value before: {:?}", messges_value);

        if let Some(messages_array) = messges_value.as_array_mut() {
            messages_array.push(Value::Object(new_message_object));
        }
        debug!("message_handler exist messages_value after: {:?}", messges_value);
        client_guard.insert("messages".to_string(), serde_json::to_string(&messges_value).unwrap());
    } else {

        let mut messages_array = json!(
            [
                {
                    "name": deserialized_params["name"],
                    "session_id": deserialized_params["session_id"],
                    "message": message.to_string(),
                    "date": Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
                    "city": deserialized_params["city"],
                    "province": deserialized_params["province"],
                },
            ]
        );
        info!("message_handler new messages: {:?}", messages_array);
        client_guard.insert("messages".to_string(), serde_json::to_string(&messages_array).unwrap());
    }

    // client_guard.insert("messages".to_string(), deserialized_string.clone());
    //
    HttpResponse::ok_redirect("http://localhost:8080/index".to_string(), response);
}